// 新闻管理部分接口
var express = require('express');
var date = require("silly-datetime");
var router = express.Router();
const Return = require("../util/utils");
var fs = require("fs");
const {
    sqlConnect
} = require('../sql/sqlUtil');
/* GET users listing. */
// 查询新闻信息(管理员)
router.get('/', function (req, res, next) {
    const page = req.query.page - 1.
    limit = req.query.limit * 1.
    is_pass = req.query.is_pass;
    let begin = page * limit;
    // 判断是否为查询
    if (req.query.searchParams == undefined) {
        // 获取数据总数
        sqlConnect(`select count(1) as count from news where is_del=0 and is_pass=${is_pass}`,function (err, data) {
            if (err) {
                console.log(err);
            } else {
                var count = data[0].count;
                var sql = `select * from news where is_del=0 and is_pass=${is_pass} order by 1 desc limit ?,?`;
                sqlConnect(sql, [begin, limit], function (err, data) {
                    if (err) {
                        console.log(err);
                    } else {
                        var json = Return.setResult();
                        json.code = 0;
                        json.count = count;
                        json.data = data;
                        res.send(json);
                    }
                })
            }
        })
       } else {
         var result = JSON.parse(req.query.searchParams);
         var title = (result.title.length == 0) ? '%' : result.title,
           date_begin = result.date_begin,
           date_end = result.date_end;
         // 计算表中符合条件信息数量
         sqlConnect(`select count(1) as count from news where is_del=0 and title like '%${title}%' and date between ? and ? and is_pass=${is_pass}`, [date_begin, date_end], function (err, data) {
           if (err) {
             console.log(err);
           } else {
             var count = data[0].count;
             var sql = `select * from news where is_del=0 and title like '%${title}%' and date between ? and ? and is_pass=${is_pass} order by 1 desc limit ?,?`;
             sqlConnect(sql, [date_begin, date_end, begin, limit], function (err, data) {
               if (err) {
                 console.log(err)
               } else {
                 var json = Return.setResult();
                 json.code = 0;
                 json.count = count;
                 json.data = data;
                 res.send(json);
               }
             })
           }
         })
       }
});
// 查询新闻信息(员工)
router.get('/staff', function (req, res, next) {
    const page = req.query.page - 1.
    limit = req.query.limit * 1.
    is_pass = req.query.is_pass,
    staff_name = req.query.staff_name;
    let begin = page * limit;
        // 获取数据总数
        sqlConnect(`select count(1) as count from news where is_del=0 and is_pass=${is_pass} and staff_name=?`,staff_name,function (err, data) {
            if (err) {
                console.log(err);
            } else {
                var count = data[0].count;
                var sql = `select * from news where is_del=0 and is_pass=${is_pass} and staff_name=? order by 1 desc limit ?,?`;
                sqlConnect(sql, [staff_name,begin, limit], function (err, data) {
                    if (err) {
                        console.log(err);
                    } else {
                        var json = Return.setResult();
                        json.code = 0;
                        json.count = count;
                        json.data = data;
                        res.send(json);
                    }
                })
            }
        })
});
// 获取指定新闻
router.get("/edit", (req, res) => {
    let id = req.query.id;
    sqlConnect("select * from news where id=?", id, (err, data) => {
        if (err) {
            return console.log(err);
        }
        return res.send(Return.setResult(200, "success", data));
    })
})
// 删除新闻信息
router.delete("/", function (req, res, next) {
    // const data = req.body;
    // var sid='';
    // // 判断是多选删除还是单选删除
    // if (!data.length) {
    //     sid = data.id;
    //     var filename = data.img_src;
    //     // 截取到图片的完整名称
    //     filename = filename.split('/')[3];
    //     // 删除图片
    //     fs.unlink("./public/upload/news/" + filename, (err) => {
    //         if (err) {
    //             console.log(err);
    //         } else {
    //             console.log("successs");
    //         }
    //     });
    // } else {
    //     for (let i = 0; i < data.length; i++) {
    //         var id = data[i].id;
    //         // 格式化id
    //         if (i != 0) {
    //             id = "," + id;
    //         }
    //         sid += id;
    //         var filename = data[i].img_src;
    //         filename = filename.split('/')[3];
    //         fs.unlink("./public/upload/news/" + filename, (err) => {
    //             if (err) {
    //                 console.log(err);
    //             }
    //         });
    //     }
    // }
    const id = req.body.id;
    let sql = `update news set is_del=1,is_using=0 where id in(${id})`;
    sqlConnect(sql, id, (err, data) => {
        if (err) {
            res.send(Return.setResult());
        } else {
            var json = Return.setResult();
            json.msg = "删除成功";
            res.send(json);
        }
    })
})
// 不通过/通过新闻
router.put('/isPass',(req,res)=>{
    const is_pass=req.body.is_pass,
    id = req.body.id;
    let sql=null,
    sqlArr=null;
    if (is_pass===1) {
        sql="update news set is_pass=? where id=?";
        sqlArr=[is_pass,id];
    }else{
        sql="update news set is_pass=?,tip=? where id=?";
        sqlArr=[is_pass,req.body.tip,id];
    }
    sqlConnect(sql,sqlArr,(err,data)=>{
        if (err) {
            return res.status(500).send(Return.setResult(500,"网络拥堵，请稍后再试！"));
        }
        return res.send(Return.setResult());
    });
})
// 添加/修改新闻
router.post("/", (req, res) => {
    try {
        const reg = /<!--\[if\s+gte\s+mso\s+9\]>(?:(?!<!\[endif\]-->)[\s\S])*<!\[endif\]-->/gi;
        const data = req.body;
        var title = data.title,
            author = data.author,
            is_using = data.is_using,
            newsID = (data.newsID)?newsID=data.newsID:newsID=-1,
            content = data.content.replace(reg, ""),
            url = data.url,
            staff_name=data.staff_name,
            has_img =(url===null)?has_img=0:has_img=1;
        const time = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
        let sql = null,
            sqlArr = null;
        // 判断是修改还是新添加
        if (newsID>0) {
            // 判断内容是否为空
            if (content === null) {
                sql = "UPDATE news SET news_img=?,title=?,author=?,date=?,is_using=?,has_img=? where id=?";
                sqlArr = [url,title, author, time, is_using,has_img,newsID];
            } else {
                sql = "UPDATE news SET news_img=?,title=?,author=?,date=?,is_using=?,content=?,has_img=? where id=?";
                sqlArr = [url,title, author, time, is_using, content,has_img,newsID];
            }

        } else {
            var is_pass=(data.role==1)?is_pass=1:is_pass=0;
            sql = "INSERT INTO news (news_img,title,author,date,is_using,content,has_img,staff_name,is_pass,is_del,read_amount) VALUES(?,?,?,?,?,?,?,?,?,0,0)";
            sqlArr = [url,title,author,time,is_using,content,has_img,staff_name,is_pass];
        }
        sqlConnect(sql, sqlArr, (err, data) => {
            if (err) {
                return console.log(err);
            }
            res.send(Return.setResult());
        })
    } catch (error) {
        console.log(error);
        res.status(500).end();
    }

})
// 员工修改新闻（变更状态为待审核）
router.post("/staff", (req, res) => {
    try {
        const reg = /<!--\[if\s+gte\s+mso\s+9\]>(?:(?!<!\[endif\]-->)[\s\S])*<!\[endif\]-->/gi;
        const data = req.body;
        var title = data.title,
            author = data.author,
            is_using = data.is_using,
            newsID = (data.newsID)?newsID=data.newsID:newsID=-1,
            content = data.content.replace(reg, ""),
            url = data.url,
            has_img =(url===null)?has_img=0:has_img=1;
        const time = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
        let sql = null,
            sqlArr = null;
            // 判断内容是否为空
            if (content === null) {
                sql = "UPDATE news SET news_img=?,title=?,author=?,date=?,is_using=?,has_img=?,is_pass=0 where id=?";
                sqlArr = [url,title, author, time, is_using,has_img,newsID];
            } else {
                sql = "UPDATE news SET news_img=?,title=?,author=?,date=?,is_using=?,content=?,has_img=?,is_pass=0 where id=?";
                sqlArr = [url,title, author, time, is_using, content,has_img,newsID];
            }
        sqlConnect(sql, sqlArr, (err, data) => {
            if (err) {
                return console.log(err);
            }
            res.send(Return.setResult());
        })
    } catch (error) {
        console.log(error);
        res.status(500).end();
    }

})
// 轮播图开关
router.put("/", (req, res) => {
    try {
        let id = req.body.id,
            is_using = req.body.is_using;
        sqlConnect("UPDATE news SET is_using=? where id=?", [is_using, id], (err, data) => {
            if (err) {
                return console.log(err);
            }
            return res.send(Return.setResult());
        })
    } catch (e) {
        console.log(e);
    }

})
module.exports = router;